<?php
/**
 * Letter model file.
 *
 * Infectamic: browser game (http://infectamic.goldzoneweb.info)
 * Copyright 2011, Loic Chardonnet
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/**
 * Class for Letter model.
 */
class Letter extends AppModel {
    var $name = 'Letter';
    var $displayField = 'name';

    var $_schema = array(
	'id' => array(
            'type' => 'integer',
            'length' => 11,
	),
	'name' => array(
            'type' => 'string',
            'length' => 255,
	),
    );

    var $hasAndBelongsToMany = array(
        'Next' => array(
            'className' => 'Letter',
            'joinTable' => 'letter_links',
            'foreignKey' => 'current_id',
            'associationForeignKey' => 'next_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        ),
    );

    /**
     * Gets letters and their links in an array.
     * 
     * @return array The letters and their links
     */
    function getLettersAndLinksInArray() {
        $lettersAndLinks = array();
        $rawLettersAndLinks = $this->find('all');
        foreach ($rawLettersAndLinks as $rawLetterAndLinks) {
            $lettersAndLinks[$rawLetterAndLinks['Letter']['name']] = array();
            foreach ($rawLetterAndLinks['Next'] as $rawLink) {
                $lettersAndLinks[$rawLetterAndLinks['Letter']['name']][$rawLink['name']] = array();
            }
        }

        return $lettersAndLinks;
    }

    /**
     * Generates a random name.
     *
     * @return string The random name
     */
    function generateRandomName() {
        $letters = $this->getLettersAndLinksInArray();
        $nbLetters = count($letters) - 1;

        $name = '';
        $nameLen = rand(MINIMUM_NAME_LENGTH, MAXIMUM_NAME_LENGTH);

        $lastLetter = array_rand($letters);
        for ($letter = 0; $letter < $nameLen; $letter++) {
            $currentLetter = array_rand($letters[$lastLetter]);
            $name .= $currentLetter;
            $lastLetter = $currentLetter;
        }

        return ucfirst($name);
    }
}
